import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author @fiber-cloud
 * @Date 2025/10/9 10:39
 * TCP回显服务器的客户端
 */
public class TcpEchoClient {

    private Socket socket = null;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        socket = new Socket(serverIP,serverPort);

    }

    public void start(){
        System.out.println("客户端启动！");

        Scanner scanner = new Scanner(System.in);

        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            while (true){

                // 1. 先从键盘上读取用户输入的内容
                System.out.print(">");
                String request = scanner.next();
                if (request.equals("exit")){
                    System.out.println("goodbye");
                    break;
                }

                // 2. 把读到的内容构造成请求, 发送给服务器.
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);

                printWriter.flush();

                // 3. 读取服务器的响应
                Scanner respScanner = new Scanner(inputStream);
                String response = respScanner.next();
                // 4. 把响应内容显示到界面上
                System.out.println(response);
            }
        }catch (IOException e){ // 4. 把响应内容显示到界面上
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }

}
